package com.huaxin.hxcloud.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.fragment.DatePickerFragment;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class ChartActivity extends BaseActivity implements
        DatePickerFragment.OnDatePickedListenner,
        View.OnClickListener {

    public static final String START = "start";
    public static final String END   = "end";
    FrameLayout    mFrameLayout;
    WebView        mWebView;
    String         fullCode;
    ProgressDialog dialog;

    private TextView startDateTv;
    private TextView endDateTv;
    private TextView mSearchTv;

    private View mNodataView;

    private Calendar startCalendar;
    private Calendar endCalendar;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_chart;
    }

    public void initView() {
        Intent intent = getIntent();
        fullCode = intent.getStringExtra("fullCode");
        mFrameLayout = (FrameLayout) findViewById(R.id.chart_frameLayout_content);
        mNodataView = findViewById(R.id.chart_data_null);
        mNodataView.setVisibility(View.GONE);
        mWebView = new WebView(getApplicationContext());
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams
                .MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mFrameLayout.addView(mWebView, params);

        startDateTv = (TextView) findViewById(R.id.chart_startDate_tv);
        endDateTv = (TextView) findViewById(R.id.chart_endDate_tv);
        mSearchTv = (TextView) findViewById(R.id.chart_search_tv);

        Date dNow = new Date();
        endCalendar = Calendar.getInstance();//默认的结束的日期 当天
        endCalendar.setTime(dNow);
        //0表示当天
        endCalendar.add(Calendar.DAY_OF_MONTH, 0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        final String endDate =sdf.format(endCalendar.getTime());

        startCalendar = Calendar.getInstance(); //默认开始日期 前一天
        startCalendar.setTime(dNow);
        //前一天  参数为1时表示后一天
        startCalendar.add(Calendar.DAY_OF_MONTH,-1);
        final String startDate= sdf.format(startCalendar.getTime());

        Log.e("lwjing","startdata:"+startDate+"endddata："+endDate);

        startDateTv.setText(startDate);
        endDateTv.setText(endDate);

        startDateTv.setOnClickListener(this);
        endDateTv.setOnClickListener(this);
        mSearchTv.setOnClickListener(this);

        dialog = new ProgressDialog(this);
        dialog.setMessage("拼命加载中...");
        dialog.setCanceledOnTouchOutside(false);
        WebSettings webSettings = mWebView.getSettings();

        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        mWebView.loadUrl("file:///android_asset/echart.html");
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(request.getUrl().toString());
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                getOptionData(startDate, endDate);
            }
        });
    }

    /**
     * 动态显示webview或加载没数据的view
     */
    private void showWebView(boolean show) {
        if (show) {
            mNodataView.setVisibility(View.GONE);
            if (mWebView != null) {
                mWebView.setVisibility(View.VISIBLE);
            }
        } else {
            mNodataView.setVisibility(View.VISIBLE);
            if (mWebView != null) {
                mWebView.setVisibility(View.GONE);
            }
        }
    }

    private void showDialog() {
        dialog.show();
    }

    private void dismissDialog() {
        dialog.dismiss();
    }

    private void getOptionData(String startDate, String endDate) {
        showDialog();
        Log.e("xxx", "xxx==?dataInfoIds=" + fullCode + "&startDate=" + startDate + "&endDate=" + endDate);
        Call<String> call = HxTransmitRequestHelper.getRequestApi().getDeviceKeyData(fullCode, endDate,
                startDate);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                final String body = response.body();
                Log.e("xxx", "xxx==指标数据：" + body);
                if (body != null) {
                    dismissDialog();
                    showWebView(true);
                    if (mWebView == null) {
                        return;
                    }
                    mWebView.post(new Runnable() {
                        @Override
                        public void run() {
                            mWebView.loadUrl("javascript:paintEcharts(" + body + ")");
                        }
                    });
                } else {
                    dismissDialog();
                    showWebView(false);
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.e("xxxxx", "===============获取数据失败" + t);
                dismissDialog();
                if (mWebView == null) {
                    return;
                }
                mWebView.post(new Runnable() {
                    @Override
                    public void run() {
                        mWebView.loadUrl("javascript:paintEcharts(" + null + ")");
                    }
                });
                showWebView(false);

            }
        });
    }

    @Override
    public void onDatePicked(String tag, int year, int month, int dayOfMonth) {
        if (START.equals(tag)) {
            startCalendar.set(year, month, dayOfMonth);
            startDateTv.setText("" + year + "-" + (month + 1) + "-" + dayOfMonth);
        } else if (tag.equals(END)) {
            endCalendar.set(year, month, dayOfMonth);
            endDateTv.setText("" + year + "-" + (month + 1) + "-" + dayOfMonth);
        }
        Log.e("xxx", "xxx==tag:" + tag + "==year:" + year + "==month:" + (month + 1) + "==day:" + dayOfMonth);
    }

    @Override
    protected void onDestroy() {

        if (mWebView != null) {
            //file:///android_asset/echart.html
            Log.i("lwjing","onDestroy webview is not null");
           // mWebView.loadDataWithBaseURL("", null, "text/html", "utf-8", null);
            mWebView.clearHistory();
           // mFrameLayout.removeView(mWebView);
            mWebView.destroy();
          //  mWebView = null;
        }
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }

        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.chart_startDate_tv:
                DatePickerFragment pickerFragmentStart = DatePickerFragment.newInstance(this, START);
                Bundle bundle1 = new Bundle();
                bundle1.putString("tag", START);
                pickerFragmentStart.setArguments(bundle1);
                pickerFragmentStart.show(getFragmentManager(), START);
                break;
            case R.id.chart_endDate_tv:
                DatePickerFragment pickerFragmentEnd = DatePickerFragment.newInstance(this, END);
                Bundle bundle2 = new Bundle();
                bundle2.putString("tag", END);
                pickerFragmentEnd.setArguments(bundle2);
                pickerFragmentEnd.show(getFragmentManager(), END);
                break;
            case R.id.chart_search_tv:
                int result = startCalendar.compareTo(endCalendar);
                if (result <= 0) {
                    String startDate = "" + startCalendar.get(Calendar.YEAR) +
                            "-" + (startCalendar.get(Calendar.MONTH) + 1) +
                            "-" + startCalendar.get(Calendar.DAY_OF_MONTH);
                    String endDate = "" + endCalendar.get(Calendar.YEAR) +
                            "-" + (endCalendar.get(Calendar.MONTH) + 1) +
                            "-" + endCalendar.get(Calendar.DAY_OF_MONTH);
                    getOptionData(startDate, endDate);
                } else {
                    Toast.makeText(this, "开始日期不能晚于截止日期", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
